//
//  BKStudentManager.m
//  I'm BKer
//
//  Created by Nguyen Van Hoa on 5/14/13.
//  Copyright (c) 2013 vanhoavn. All rights reserved.
//

#import "BKStudentManager.h"
#import "SBJson.h"

#define kKeyForMSSV @"Key for MSSV"
#define kKeyForMSSVDict @"Key for MSSVDict"
#define kKeyForMSSVKey @"Key for MSSVKey"

static NSRegularExpression* mssvRegex = NULL;
static NSString* loadedMSSV = @"";
static NSDictionary* mDict = NULL;

@implementation BKStudentManager
+(void)initialize
{
    mssvRegex = [NSRegularExpression regularExpressionWithPattern:@"^[2-9KGV][0-9]{7}$" options:NSRegularExpressionCaseInsensitive error:NULL];
}
+ (NSString*) mssv
{
    return [[NSUserDefaults standardUserDefaults] stringForKey:kKeyForMSSV];
}
+ (NSDictionary*) getDictionary
{
    if([loadedMSSV compare:[self mssv]]==NSOrderedSame && mDict!=NULL) return mDict;
    loadedMSSV = [[NSUserDefaults standardUserDefaults] objectForKey:kKeyForMSSVKey];
    mDict = [[NSUserDefaults standardUserDefaults] objectForKey:kKeyForMSSVDict];
    if([loadedMSSV compare:[self mssv]]==NSOrderedSame && mDict!=NULL) return mDict;
    [self loadInfo];
    [self saveDictionary];
    return mDict;
}
+ (void)saveDictionary
{
    if(mDict!=NULL){
        [[NSUserDefaults standardUserDefaults] setObject:mDict forKey:kKeyForMSSVDict];
        [[NSUserDefaults standardUserDefaults] setObject:loadedMSSV forKey:kKeyForMSSVKey];
    }
}
+ (BOOL)validateMSSV:(NSString *)mssv
{
    return mssv != NULL && [mssvRegex firstMatchInString:mssv options:0 range:NSMakeRange(0, [mssv length])].range.length>0;
}
+ (BOOL) setMSSV: (NSString*)mssv
{
    if(mssv!=NULL && [self validateMSSV:mssv]){
        mDict = NULL;
        [[NSUserDefaults standardUserDefaults] setObject:mssv forKey:kKeyForMSSV];
        return YES;
    }
    return NO;
}
+ (BOOL)requireMSSV
{
    return ![self validateMSSV:[self mssv]];
}
+ (NSArray *)danhSachLichThi
{
    return [mDict objectForKey:@"lichThi"];
}
+ (NSArray *)danhSachTKB
{
    return [mDict objectForKey:@"tkb"];
}
+(NSDictionary *)danhSachDiem
{
    return [mDict objectForKey:@"diem"];
}
+(BOOL)loadInfoLocalFirst
{
    [self getDictionary];
    return ([loadedMSSV compare:[self mssv]]==NSOrderedSame && mDict!=NULL);
}
+ (BOOL)loadInfo
{
    if([self requireMSSV]) return NO;
    SBJsonParser *parser = [[SBJsonParser alloc] init];
    NSString* url = [NSString stringWithFormat:@"http://www.vhn.vn/l/bkhcm/?mssv=%@",[self mssv]];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if(!response) return NO;
    NSString *json_string = [NSString stringWithUTF8String:[response bytes]];
    mDict = [parser objectWithString:json_string error:nil];
    loadedMSSV = [NSString stringWithString:[self mssv]];
    NSLog(@"%@",mDict);
    return YES;
}
@end
